package com.gongpingjialoan.activity.car;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseScrollFragment;
import com.gongpingjialoan.activity.main.ValueReportActivity;
import com.gongpingjialoan.adapter.EvalAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AssessHistory;
import com.gongpingjialoan.bean.AssessmentData;
import com.gongpingjialoan.network.NetDataJson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/5/13.
 */
public class EvalFragment extends BaseScrollFragment implements View.OnClickListener, NetDataJson.OnNetDataJsonListener, AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener<ListView>, PullToRefreshBase.OnLastItemVisibleListener {

    private NetDataJson mNetDataJson;

    private View view, footView;

    private ImageView nodataImageView;

    private ListView listView;

    private PullToRefreshListView pullToRefreshListView;

    private List<AssessHistory> mAssessHistories;

    private EvalAdapter mEvalAdapter;

    public int mPage;

    public boolean mIsLoadingMore = true;

    public boolean mHasMore;

    public boolean isRefresh;

    private int type = -1 ;

    private String callType = "eval_sell";

    public EvalFragment(int type) {
        this.type = type;
        if(type == 0 ){
            callType = "eval_sell";
        }else{
            callType = "eval_buy";
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.eval_fragment, container, false);
        footView = inflater.inflate(R.layout.listview_footview, null);
        nodataImageView = (ImageView) view.findViewById(R.id.no_info);
        pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnLastItemVisibleListener(this);

        mAssessHistories = new ArrayList<>();
        mEvalAdapter = new EvalAdapter(mAssessHistories, getActivity());
        listView = pullToRefreshListView.getRefreshableView();
        listView.addFooterView(footView);
        listView.setAdapter(mEvalAdapter);
        listView.setOnItemClickListener(this);
        listView.removeFooterView(footView);

        mNetDataJson = new NetDataJson(this);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                pullToRefreshListView.setRefreshing();
            }
        }, 300);
        return view;
    }


    @Override
    public void onClick(View v) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) return;
        AssessHistory ah = (AssessHistory) view.getTag(R.id.tag_second);
        AssessmentData data = AssessmentData.getInstance();
        data.clear();
        data.setBrandName(ah.brand);
        data.setBrandSlug(ah.brand_slug);
        data.setMile(ah.mile);
        data.setModelDetailName(ah.model_detail);
        data.setModelDetailSlug(ah.model_detail_slug);
        data.setModelName(ah.model);
        data.setModelSlug(ah.model_slug);
        data.setModelThumbnail(ah.url);
        data.setMonth(ah.month);
        data.setYear(ah.year);
//        data.setType(getType());
        data.setCity(ah.city);
        data.setCar_id("");


        if(type == 0) {
            Intent it = new Intent(getActivity(), ValueReportActivity.class);
            it.putExtra("isassessment", true);

            String weburl = API.assessCarUrl
                    + data.getBrandSlug() + "/" + data.getModelSlug()
                    + "/" + data.getModelDetailSlug() + "/"
                    + data.getYear() + "-" + data.getMonth() + "/"
                    + data.getMile() + "/";


            it.putExtra("url", weburl);
            it.putExtra("title", "估值报告");
            it.putExtra("content", "");
            it.putExtra("isassessment", true);
            getActivity().startActivity(it);
        }else{
            Intent it = new Intent(getActivity(),
                    NewUseCarAssResultActivity.class);
            getActivity().startActivity(it);
        }

    }


    private void refresh() {
        mPage = 1;
        mHasMore = true;
        isRefresh = true;
        nodataImageView.setVisibility(View.GONE);
        updateData();

    }


    private void updateData() {
        mNetDataJson.cancelTask();
        mNetDataJson.addParam("page", mPage);
        mNetDataJson.addParam("record_type", callType);
        mNetDataJson.setUrl(API.collectHistory);
        mNetDataJson.request("get");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
            mNetDataJson = null;
        }
    }




    @Override
    public void onLastItemVisible() {
        if (!mHasMore) {
            //Toast.makeText(getActivity(), "没有更多了", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!mIsLoadingMore && mHasMore) {
            listView.addFooterView(footView);
            listView.setSelection(listView.getBottom());
            isRefresh = false;
            mIsLoadingMore = true;
            mPage++;
            updateData();
        }
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        mIsLoadingMore = false;
        Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        JSONArray jsonArray = null;
        if (isRefresh) {
            mAssessHistories.clear();
            mEvalAdapter.setData(mAssessHistories);
        }
        try {
            jsonArray = json.getJSONArray("records");
            if (0 == jsonArray.length()) {
                mIsLoadingMore = false;
                nodataImageView.setVisibility(View.VISIBLE);
                pullToRefreshListView.onRefreshComplete();
                return;
            }

            for (int i = 0; i < jsonArray.length(); i++) {
                AssessHistory ah = new AssessHistory();
                JSONObject object = jsonArray.getJSONObject(i);
                ah.model_detail = object.getString("model_detail");
                ah.model_slug = object.getString("model_slug");
                ah.brand = object.getString("brand");
                ah.model_detail_slug = object.getString("model_detail_slug");
                ah.create_time = object.getString("create_time");
                ah.mile = object.getString("mile");
                ah.eval_price = object.getString("eval_price");
                ah.year = object.getString("year");
                ah.month =  object.getString("month");
                ah.brand_slug = object.getString("brand_slug");
                ah.model = object.getString("model");
                ah.url = object.getString("thumbnail");
                ah.record_id = object.getString("record_id");
                ah.city = object.getString("city");
                ah.eval_price_change = object.getString("eval_price_change");
                mAssessHistories.add(ah);
            }
            int page_num = json.getInt("total_page");
            if (page_num == mPage) {
                mHasMore = false;
            }
        } catch (JSONException e) {
            mIsLoadingMore = false;
            nodataImageView.setVisibility(View.VISIBLE);
            Toast.makeText(getActivity(), "数据异常，请稍后再试", Toast.LENGTH_SHORT).show();
            pullToRefreshListView.onRefreshComplete();
            return;
        }
        mEvalAdapter.setData(mAssessHistories);
        pullToRefreshListView.onRefreshComplete();
        mIsLoadingMore = false;
    }

    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (!isFristLoading) {
            String label =
                    "更新时间:" + DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        }
        isFristLoading = false;
        refresh();
    }
}
